package br.org.credfaz.sis.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import br.org.credfaz.sis.Db2ConnectionFactory;
import br.org.credfaz.sis.MysqlConnectionFactory;
import br.org.credfaz.sis.modelo.ExtContaCorrente;

public class ExtContaCorrenteDAO {
	
	private final Connection connection;
	private final Connection connectionLocal;

	public ExtContaCorrenteDAO() {
		try {
			connection = new Db2ConnectionFactory().getConnection();
			connectionLocal = new MysqlConnectionFactory().getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void atualizar() {
		try {
			
			SimpleDateFormat ano = new SimpleDateFormat("yyyy");
			Date meses = new Date();
			@SuppressWarnings("deprecation")
			Integer resultado = meses.getMonth();
			String anoMesPesquisa;
			if (resultado < 10) {
				anoMesPesquisa = "0"+ resultado + ano.format(meses);
			}else{
				anoMesPesquisa = resultado + ano.format(meses);
			}
			PreparedStatement stmt = this.connection
					.prepareStatement("select mesano, numcontacorrente, numcontavinculada, valorlimite from coopcons.extcontacorrente where mesano = ?");
			stmt.setString(1, anoMesPesquisa);
			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				gravaECc(rs);
			}
			rs.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private void gravaECc(ResultSet rs) throws SQLException {
		ExtContaCorrente ecc = new ExtContaCorrente();
		ecc.setMesano(rs.getString("mesano"));
		ecc.setNumcontacorrente(rs.getLong("numcontacorrente"));
		ecc.setNumcontavinculada(rs.getLong("numcontavinculada"));
		ecc.setValorlimite(rs.getBigDecimal("valorlimite"));
		adiciona(ecc);
	}
	
	private void adiciona(ExtContaCorrente extcc){
		String sql = "insert into extcontacorrente (mesano, numcontacorrente, numcontavinculada, valorlimite) values (?, ?, ?, ?)";
		PreparedStatement stmt;
		try{
			stmt = connectionLocal.prepareStatement(sql);
			stmt.setString(1, extcc.getMesano());
			stmt.setLong(2, extcc.getNumcontacorrente());
			stmt.setLong(3, extcc.getNumcontavinculada());
			stmt.setBigDecimal(4, extcc.getValorlimite());
			stmt.execute();
			
		}catch (SQLException e){
			throw new RuntimeException(e);
		}
	}

}
